﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Web.Security;
using System.Web;
using System.IO;

namespace Rainy.FrameWork
{
    /// <summary>
    /// 系统用户操作类
    /// </summary>
    public class RainyUser
    {
        DataOperation dataOperation = new DataOperation();
        private EnumPlatfrom currentPlatfrom;
        private string userId;
        private string _userCacheKey = null;
        /// <summary>
        /// 用户信息缓存键
        /// </summary>
        private string UserCacheKey
        {
            get
            {
                if (_userCacheKey == null)
                {
                    _userCacheKey = string.Format("{0}_{1}_CurrentUser", currentPlatfrom.ToString(), userId);
                }

                return _userCacheKey;
            }
        }
        private string _roleCacheKey = null;
        /// <summary>
        /// 角色信息缓存键
        /// </summary>
        private string RoleCacheKey
        {
            get
            {
                if (_roleCacheKey == null)
                {
                    _roleCacheKey = string.Format("{0}_{1}_RoleList", currentPlatfrom.ToString(), userId);
                }
                return _roleCacheKey;
            }
        }
        public RainyUser()
        {
        }
        public RainyUser(EnumPlatfrom currentPlatfrom, string userId)
        {
            this.currentPlatfrom = currentPlatfrom;
            this.userId = userId;
        }
        /// <summary>
        /// 内部获取用户信息
        /// </summary>
        /// <returns></returns>
        internal UserInfo GetUserInfo()
        {
            UserInfo currentUser = (UserInfo)System.Web.HttpContext.Current.Cache[UserCacheKey];

            if (currentUser == null)
            {
                UserInfo userInfo = new UserInfo();

                DataOperation dataOperation = new DataOperation();
                DataRow drow = dataOperation.GetRow(Tables.UserInfo, "AccountID='" + userId + "'");

                if (drow != null)
                {
                    userInfo.AccountID = drow["AccountID"].ToString();
                    userInfo.LogName = drow["LogName"].ToString();
                    userInfo.MemberType = (EnumMemberType)Enum.Parse(typeof(EnumMemberType), drow["MemberType"].ToString());
                    userInfo.UserName = drow["UserName"].ToString();
                }


                System.Web.HttpContext.Current.Cache.Add(UserCacheKey, userInfo, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15), System.Web.Caching.CacheItemPriority.Default, null);

                return userInfo;
            }
            else 
                return currentUser;
            
        }
        /// <summary>
        /// 内部获取用户角色列表(可含角色编号和角色名)
        /// </summary>
        /// <returns></returns>
        internal List<string> GetRoleList()
        {
            List<string> currentRoleList = (List<string>)System.Web.HttpContext.Current.Cache[RoleCacheKey];

            if (currentRoleList == null)
            {
                List<string> roleList = new List<string>();

                switch (currentPlatfrom)
                {
                    case EnumPlatfrom.Web:

                        break;
                    case EnumPlatfrom.Manage:

                        break;
                    default:
                        break;

                }
                System.Web.HttpContext.Current.Cache.Add(RoleCacheKey, roleList, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15), System.Web.Caching.CacheItemPriority.Default, null);

                return roleList;
            }
            else
                return currentRoleList;
           
        }
        /// <summary>
        /// 用户退出
        /// </summary>
        public void UserLogout()
        {
            System.Web.HttpContext.Current.Cache.Remove(UserCacheKey);
            System.Web.HttpContext.Current.Cache.Remove(RoleCacheKey);

            //清除验证票据
            FormsAuthentication.SignOut();
        }
        /// <summary>
        /// 验证用户
        /// </summary>
        /// <param name="currentPlatfrom">当前平台</param>
        /// <param name="loginName">登录号</param>
        /// <param name="pwd">密码</param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool TryUserLogin(EnumPlatfrom currentPlatfrom,string loginName, string pwd, out string message)
        {
            bool flag = false;

            message = "已验证通过";

            try
            {
                DataOperation dataOperation = new DataOperation();

                //验证账户是否停用
                //flag = Convert.ToBoolean(dataOperation.GetParamScalar(Tables.UserInfo, "count(0)", "IsActive = 0 AND LogName=@LogName and RegisterID=@RegisterID", new object[] { loginName, currentPlatfrom.ToString()}));

                if (flag)
                {
                    message = "该账户已经停用！";
                    return false;
                }

                //验证帐号和密码

                //object result = dataOperation.GetParamScalar(Tables.UserInfo, "AccountID", "LogName=@LogName and Password=@Password and RegisterID=@RegisterID", new object[] { loginName, System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5"), currentPlatfrom.ToString() });

                //if (result == null || result == Convert.DBNull)
                //{
                //    message = "用户名或密码有误！";
                //    return false;
                //}
            }
            catch (Exception ex)
            {
                message = "系统错误，请查看日志:" + ex.Message;
            }

            return flag;
        }

        /// <summary>
        /// 注册新用户
        /// </summary>
        /// <param name="logname">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="name">姓名</param>
        /// <param name="email">电子邮件</param>
        /// <param name="address">联系地址</param>
        /// <param name="postcode">邮政编码</param>
        /// <returns>True,False</returns>
        public bool UserRegedit(string logname, string password, string name, string email, string address, string postcode)
        {
            bool ret = false;
            //string guid = System.Guid.NewGuid().ToString();
            //string sqlbase = "insert into MemberBase (MainID,LogName,LogPassword,Type,ISActive,CreateTime) ";
            //sqlbase += "values ('" + guid + "','" + logname + "','" + password + "','DB',1,'" + System.DateTime.Now.ToString() + "')";

            //string sqlinfo = "insert into MemberInfo (MainID,LogName,Name,Address,Email,PostCode,CreateTime) ";
            //sqlinfo += "values ('" + System.Guid.NewGuid().ToString() + "','" + logname + "','" + name + "','" + address + "','" + email + "','" + postcode + "','" + System.DateTime.Now.ToString() + "')";
            //if (DA.ExecuteSql(sqlbase))
            //{
            //    if (DA.ExecuteSql(sqlinfo))
            //    {
            //        ret = true;
            //    }
            //    else
            //    {
            //        string sqldel = "delete from MemberBase where MainID='" + guid + "'";
            //        DA.ExecuteSql(sqldel);
            //    }
            //}
            return ret;
        }
        /// <summary>
        /// 检测帐号是否已经存在
        /// </summary>
        /// <param name="logname">用户名</param>
        /// <returns>True,False</returns>
        public bool CheckUp(string logname)
        {
            bool ret = false;
            if (logname == "123123")
            {
                ret = true;
            }
            //string sql = "select MainID from MemberBase where LogName='" + logname + "'";
            //DataTable dt = DA.ExecuteDataTable(sql);
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    ret = true;
            //}
            return ret;
        }

        /// <summary>
        /// 保存Session
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public string Authenticate(string username, string password)
        {
            string ret = IsValidUser(username, password).ToString();
            if (ret == "pass")
            {
                HttpContext.Current.Session["LogName"] = username;
            }
            return ret;
        }

        /// <summary>
        /// 判断用户登陆，数据库提取信息
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public string IsValidUser(string username, string password)
        {
            //根据参数检索数据库中有无此用户
            string ret = "用户名或密码错误!";
            //DataOperation dataOperation = new DataOperation();
            //string sql = "select LogPassword from MemberBase where LogName ='" + username + "'";
            //DataSet dst = dataOperation.GetDataSet(sql);
            //if (dst != null && dst.Tables[0].Rows.Count > 0)
            //{
            //    string resultpassword = dst.Tables[0].Rows[0]["LogPassword"].ToString();
            //    dst.Clear();
            //    dst.Dispose();
            //    //返回值，生成form验证票
            //    if (string.Compare(password, resultpassword, false) == 0)
            //    {
            //        ret = "pass";
            //    }
            //}
            if (username == "123123")
            {
                ret = "pass";
            }
            return ret;
        }

        /// <summary>
        /// 判断当前页面是否需要登录
        /// </summary>
        /// <param name="formid"></param>
        /// <returns></returns>
        public bool IsLogin(string formid)
        {
            bool ret = true;
            XmlOperation xmlOperation = new XmlOperation();
            string xmlPath = WebConfig.SystemXmlPath + "SiteConfig\\"+formid+".xml";
            if (File.Exists(xmlPath))
            {
                XmlNode node = xmlOperation.LoadXml(xmlPath);
                if(node.Attributes["AccessRoles"].Value != "所有用户")
                {
                    //--添加验证是否登录方法
                    ret = false;
                }
            }
            return ret;
        }
    }
}
